clear all
set more off
tempfile ubigeo temp

/*

This dofile pulls in raw ENAHO data from the individual's education module (300) and saves the outcome (300.dta) in the "working" directory

*/

** PATHS
local data ../data/enaho
local working ../working

**** 2004-2016
forvalues year = 2004/2016 {
	use `data'/`year'/300, clear
	
	recode p300a (1 2 3 = 1) (4 = 0) (5 6 7 8 = 0) (9 = .), gen(native)
	recode p300a (1 2 3 = 0) (4 = 1) (5 6 7 8 = 0) (9 = .), gen(spanish)
	recode p300a (1 2 3 = 0) (4 = 0) (5 6 7 8 = 1) (9 = .), gen(foreign)
	
	duplicates drop conglome vivienda hogar codperso, force

	recode p301a (1 2 3 = 1) (4 5 = 0) (6 7 9 = 0) (8 = 0) (10 11 = 0) (else = .), gen(educ_0)
	recode p301a (1 2 3 = 0) (4 5 = 1) (6 7 9 = 0) (8 = 0) (10 11 = 0) (else = .), gen(educ_1)
	recode p301a (1 2 3 = 0) (4 5 = 0) (6 7 9 = 1) (8 = 0) (10 11 = 0) (else = .), gen(educ_2)
	recode p301a (1 2 3 = 0) (4 5 = 0) (6 7 9 = 0) (8 = 1) (10 11 = 0) (else = .), gen(educ_3)
	recode p301a (1 2 3 = 0) (4 5 = 0) (6 7 9 = 0) (8 = 0) (10 11 = 1) (else = .), gen(educ_4)
	
	drop if p208a < 16

	cap destring p301b p301c, replace
	egen anios = rowmax(p301b p301c)
	replace anios = 0 if p301a <= 2
	gen schooling = 0 if p301a != .	
	replace schooling = anios if p301a <= 3
	replace schooling = 6 if p301a == 4
	replace schooling = 6 + anios if p301a == 5
	replace schooling = 11 if p301a == 6
	replace schooling = 11 + anios if p301a >= 7 & p301a <= 10
	replace schooling = 16 + anios if p301a == 11
	
	recode p303 (2 = 0), gen(asiste)

	keep con viv hog codper educ_* schooling native foreign spanish asiste
	gen year = `year'

	** SAVE
	cap destring con viv hog codper, replace
	compress
	save `working'/300_`year', replace
}

use `working'/300_2004, clear
forvalues y = 2005/2016 {
	append using `working'/300_`y'
}	

forvalues y = 2004/2016 {
	erase `working'/300_`y'.dta
}	

** SAVE
compress
save `working'/300, replace
